import { RouteObject, Navigate } from 'react-router-dom'
import { Suspense } from 'react'
import Loading from '@/pages/Loading'
import { sessionGetItem } from '../utils/auth'
import asyncRouter from './asyncRouter'
import type { MenuProps } from 'antd'
import routes from './index'
// 路由处理方式
export type MenuItem = Required<MenuProps>['items'][number]
export type ItemType = {
  label: React.ReactNode
  key: React.Key
  icon?: React.ReactNode
  children?: MenuItem[]
  type?: 'group'
}
function getMenuItem(
  label: React.ReactNode,
  key: React.Key,
  icon?: React.ReactNode,
  children?: MenuItem[],
  type?: 'group'
): MenuItem {
  return {
    key,
    icon,
    children,
    label,
    type
  } as MenuItem
}
export const getMenu = (
  routerList: SyncRoute['DefaultRoutes'],
  path: React.Key | undefined
): MenuItem[] => {
  const result =
    routerList.children &&
    routerList.children.map((item: SyncRoute['AsyncRoutes']) => {
      if (!item.children) {
        return getMenuItem(item.meta.title, `${path}/${item.path as string}`, item.meta.icon)
      }
      if (item.children) {
        const key = `/${item.path as string}`
        const getItemObj = getMenuItem(
          item.meta.title,
          `${path}/${item.path as string}`,
          item.meta.icon
        )
        return getMenuItem(item.meta.title, key, item.meta.icon, getMenu(item, getItemObj?.key))
      }
    })
  return result as MenuItem[]
}
function isRedirect(route: SyncRoute['DefaultRoutes']) {
  if (!route.element) {
    if (route.redirect) {
      return (
        <Suspense fallback={<Loading />}>
          <Navigate to={route.redirect} replace={true} />
        </Suspense>
      )
    }
    return (
      <Suspense fallback={<Loading />}>
        <route.component />
      </Suspense>
    )
  }
  if (route.element) {
    return route.element
  }
}
// 获取路由组件
export const generateRouter = (routers: SyncRoute['DefaultRoutes'][]): RouteObject[] => {
  let mRouteTable: RouteObject[] = []
  routers.forEach(route => {
    mRouteTable.push({
      path: route.path,
      element: isRedirect(route),
      children: route.children && generateRouter(route.children)
    })
  })
  return mRouteTable
}
// 获取带有权限的路由
const getAsyncRoute = (Permissions: Array<string>) => {
  const result = asyncRouter.filter(item => Permissions.includes(item.name as string))
  return result
}
// 遍历路由
const eachRouter = (
  itemList: SyncRoute['DefaultRoutes'][],
  router: SyncRoute['DefaultRoutes'][]
) => {
  const itemRouterNameLIst = itemList.map(item => item.name)
  for (let i = 0; i < router.length; i++) {
    if (!itemRouterNameLIst.includes(router[i].name)) {
      itemList.push(router[i])
    } else {
      continue
    }
  }
}
// 判断路由权限
export const filterRouter = (
  router: SyncRoute['DefaultRoutes'][]
): SyncRoute['DefaultRoutes'][] => {
  const token = sessionGetItem('token')
  let result: SyncRoute['DefaultRoutes'][] = []
  if (token) {
    const username = sessionGetItem('username')
    const layoutRouter = router.map(item => {
      if (item.path === '/' && item.children) {
        const filterArr = getAsyncRoute(['homepage'])
        const result = username === 'admin' ? asyncRouter : filterArr
        eachRouter(item.children, result)
      }
      return item
    })
    result = layoutRouter
  } else {
    result = router.filter(item => item.path !== '/')
  }
  return result
}
export const RouterList = () => {
  const asyncRouter = filterRouter(routes)
  const filterList = asyncRouter.find(item => item.path === '/')!
  return filterList
}
const getRouterList = () => {
  const asyncRouter = generateRouter(filterRouter(routes))
  return asyncRouter
}

export default getRouterList
